package com.example.jucdemo.waitnotify.dmeo1;

import java.util.List;

/**
 * @Author by KoVaVo
 * @Date 2023-05-20 18:42
 * @Desc:
 */
public class Code_02_MyService {

    private Object lock = new Object();

    private Code_01_MyList myList = new Code_01_MyList();

    //wait 方法
    public void waitMethod(){
        try {
            synchronized (lock){
                if(myList.size() != 5){
                    System.out.println("begin wait" + System.currentTimeMillis() + "  " + Thread.currentThread().getName());
                    lock.wait();
                    System.out.println("end wait" + System.currentTimeMillis() + "  " + Thread.currentThread().getName());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //notify 方法
    public void notifyMethod(){
        try {
            synchronized (lock){
                System.out.println("begin notify " + System.currentTimeMillis() + "  " + Thread.currentThread().getName());
                for (int i = 0; i < 10; i++) {
                    myList.add();
                    if(myList.size() == 5){
                        lock.notify();
                        System.out.println("我只是发出通知而已，wait后面的代码并没有立即执行，因为锁还没有释放。。。");
                    }
                    System.out.println("add 次数 " + (i + 1));
                }

                System.out.println("end wait " + System.currentTimeMillis() + "  " + Thread.currentThread().getName());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
